package br.com.locanet.persistence.properties.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import br.com.locanet.persistence.properties.FilePersister;

public class PropertiePersister implements FilePersister {
	
	@Override
	public void del(String file, String attribute) {
		try {
			InputStream stream = getInputStream(file);
			Properties prop = getPropertie(stream);
			prop.remove(attribute);
			stream.close();
		} catch (IOException e) {
		}
	}

	@Override
	public String get(String file, String attribute) {
		try {
			InputStream stream = getInputStream(file);
			Properties prop = getPropertie(stream);
			String value = prop.getProperty(attribute);
			stream.close();
			return value;
		} catch (IOException e) {
		}
		return null;
	}

	@Override
	public void set(String file, String attribute, String value) {
		Properties prop = new Properties();
		try {
			InputStream stream = getInputStream(file);
			prop = getPropertie(stream);
			prop.setProperty(attribute, value);
			if (stream!=null) stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try{
			FileWriter fileWriter = getFileWriter(file);
			prop.store(fileWriter, "Properties LocaNet");
			fileWriter.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private Properties getPropertie(InputStream stream) throws IOException {
		Properties prop = new Properties();
		if (stream != null)
			prop.load(stream);
		return prop;
	}

	private InputStream getInputStream(String file)
			throws IOException {
		return new FileInputStream(getFile(file));
	}

	private FileWriter getFileWriter(String file)
			throws IOException {
		return new FileWriter(getFile(file));
	}
	
	private File getFile(String file){
		return new File(getClass().getResource(file).getFile().replace("%20", " "));
	}

}
